Convert hwnd to Process Name using vb.net

Good morning everyone. I had a pretty lousy day yesterday. Teh specs on my email project got turned upside down yesterday and then wasted a lot of time at the DMV then finding out I was going to have to come back the next day anyway. Oh well. It’s gotta get better today.

Well anyway, the title petty much says it all in this case. We want to return the actual process name the hwnd represents. Make it a great day!

Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Lst = ListBox1      '--------> ADD THIS LINE
        EnumWindows(AddressOf EnumWindowsCallBack, 0)
    End Sub
End Class
 
 
Module Module1
    Private Declare Auto Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hWnd As IntPtr, 
ByRef ProcessID As Integer) As Integer
 
    Public Lst As ListBox
 
    Public Delegate Function EnumWindowsProc(ByVal hwnd As IntPtr, ByVal lParam As Int32) As Int32
 
    Public Declare Function EnumWindows Lib "user32.dll" _
            (ByVal lpEnumFunc As EnumWindowsProc, ByVal lParam As Int32) As Int32
 
    Public Declare Function GetWindowTextLength Lib "user32.dll" Alias "GetWindowTextLengthA" _
        (ByVal hwnd As IntPtr) As Int32
 
    Public Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" _
        (ByVal hwnd As IntPtr, ByVal lpString As String, ByVal cch As Int32) As Int32
 
    'Callback function to enum windows
    Public Function EnumWindowsCallBack(ByVal hwnd As IntPtr, ByVal lParam As Int32) As Int32
        Dim sSave As String
        Dim ProcessID As Long
 
        GetWindowThreadProcessId(hwnd, ProcessID)
 
        Dim processLB As Process
        Dim tempProc As Process = processLB.GetProcessById(ProcessID)
 
        Dim processName As String = tempProc.ProcessName
 
        If (processName = "notepad") Then
 
 
            'Get the windowtext length
            sSave = Space(GetWindowTextLength(hwnd) + 1)
 
            'get the window text
            GetWindowText(hwnd, sSave, Len(sSave))
 
            'remove the last Chr(0)
            sSave = Microsoft.VisualBasic.Left(sSave, Len(sSave) - 1)
 
            'Error below: Reference to a non-shared member requires an Object Reference
            Lst.Items.Add(sSave)
            'Lst.Items.Add(processName)
 
 
            If sSave.Trim <> "" Then
                Debug.WriteLine(sSave)
            End If
        End If
        Return 1 'continue enumeration        
    End Function
 
End Module
 
  1. Leave a comment

Leave a comment